package com.sh.personnel.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sh.personnel.domain.ITbRole;
import com.sh.personnel.mapper.IRoleMapper;
import com.sh.personnel.service.IRoleService;
import com.sh.personnel.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;

/**
 * @author 林思浩
 * @date 2020/03/16 13:33
 */
@Service
public class IRoleServiceImpl implements IRoleService {

    @Autowired
    IRoleMapper roleMapper;

    @Override
    public List<HashMap<String, String>> getRoleIdAndName() {
        List<HashMap<String, String>> list = roleMapper.findRoleIDAndName();
        return list;
    }

    @Override
    public PageInfo<ITbRole> getRoleList(Integer page, String key) {
        PageHelper.startPage(page, 9);
        List<ITbRole> list = roleMapper.findRoleList(key);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public boolean addRoleNew(ITbRole role) {
        role.setCreatetime(TimeUtil.currentMillis());
        List<Integer> menuIds = role.getMenuIds();
        int result = roleMapper.insertRole(role);
        if(menuIds != null) {
            roleMapper.insertRoleMenu(role.getId(), menuIds);
        }
        return result>0 ? true : false;
    }

    @Override
    public ITbRole getRoleById(String roleId) {
        ITbRole role = roleMapper.findRoleById(roleId);
        return role;
    }

    @Override
    @Transactional
    public boolean updateRoleById(ITbRole role) {
        if(roleMapper.deleteRoleMenuByRoleId(role.getId()) >= 0) {
            List<Integer> menuIds = role.getMenuIds();
            if(!ObjectUtils.isEmpty(menuIds)) {
                roleMapper.insertRoleMenu(role.getId(), menuIds);
            }
        }
        int result = roleMapper.updateRoleById(role);
        return result>0 ? true : false;
    }

    @Override
    public boolean deleteRoleById(String roleId) {
        int result = roleMapper.deleteRoleById(roleId);
        return result>0 ? true : false;
    }
}
